package opvas;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.IOUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class SSHLinux {

    public static String exeCommand(String host, int port, String user, String password, String command) throws JSchException, IOException {
        JSch jsch = new JSch();
        Session session = jsch.getSession("root", "192.168.211.136");
        session.setConfig("StrictHostKeyChecking", "no");
        //    java.util.Properties config = new java.util.Properties();
        //   config.put("StrictHostKeyChecking", "no");
        session.setPassword(password);
        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand(command);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        String result = new BufferedReader(new InputStreamReader(in))
                .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
        //  String out = IOUtils.toString(in, "UTF-8");
        channelExec.disconnect();
        session.disconnect();

        return result;
    }

    public static void main(String[] args) throws JSchException, IOException {
        JSch jsch = new JSch();
        Session session = jsch.getSession("root", "192.168.13.117");
        session.setConfig("StrictHostKeyChecking", "no");
        //    java.util.Properties config = new java.util.Properties();
        //   config.put("StrictHostKeyChecking", "no");
        session.setPassword("contrail123");
        session.connect();

        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        InputStream in = channelExec.getInputStream();
        channelExec.setCommand("IPLIST=\"192.168.11.13\" /root/goWeakPass/goWeakPass");
        channelExec.setErrStream(System.err);
        channelExec.connect();
//        String result = new BufferedReader(new InputStreamReader(in))
//                .lines().parallel().collect(Collectors.joining(System.lineSeparator()));
        Stream<String> lines = new BufferedReader(new InputStreamReader(in)).lines();
        List<String> collect = lines.collect(Collectors.toList());
        //  String out = IOUtils.toString(in, "UTF-8");
        channelExec.disconnect();
        session.disconnect();
//        System.out.println(collect);
        for (String s : collect) {
            System.out.println(s);
        }
    }
}